import requests
import json
import base64
import time
from aip import AipSpeech

class BaiDuApiAudioToText():
    def __init__(self, config,audioFile, file_type="wav", rate=16000):
        self.audioFile = audioFile
        self.file_type = file_type
        self.rate = rate
        self.config = config
        # 百度语音 API # APi 文档
        self.APP_ID = self.config['baidu_api']['app_id']
        self.API_KEY = self.config['baidu_api']['api_key']
        self.SECRET_KEY = self.config['baidu_api']['secret_key']

        self.client = AipSpeech(self.APP_ID, self.API_KEY, self.SECRET_KEY)


    def get_result_FastApi(self):
      '''百度短语音识别API'''
      try:
          response = self.client.asr(get_file_content(self.audioFile), self.file_type, self.rate, {
            'dev_pid': 1537,
            })
          if response['err_no'] != 0 :
              raise Exception("BaiDuApiAudioToText error: ",response)
          return response['result'][0]
      except Exception as e:
          raise e


def get_file_content(filePath):
      try:
          with open(filePath, 'rb') as fp:
            return fp.read()
      except Exception as e:
          raise e

    

